package com.syh.bishe.controller;

import com.syh.bishe.pojo.Result;
import com.syh.bishe.pojo.User;
import com.syh.bishe.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

/**
 * @author syh 86187
 * @date 2024/6/30
 * com.syh.bishe.controller
 * @description  api
 */
@Tag(name = "UserController", description = "用户模块")
@RestController
@RequiredArgsConstructor
public class UserController {
    private final UserService userService;
    @PostMapping("/user/login")
    @Transactional
    @Operation(summary = "用户登录")
    public Result login(@RequestBody User user) {
        User login = userService.login(user);
        if (login == null) {
            return Result.error("用户名或密码错误,或者账号被锁定");
        }
        return Result.success(login);
    }
    @PostMapping("/user/register")
    @Transactional
    @Operation(summary = "用户注册")
    public Result register(@RequestBody User user) {
        User register = userService.register(user);
        if (register!=null) {
            return Result.success(register);
        }
        return Result.error("注册失败");
    }
    @PostMapping("/user/reset-password")
    @Operation(summary = "重置密码")
    @Transactional
    public Result reset(@RequestBody User user) {
        if (userService.reset(user)) {
            return Result.success();
        }
        return Result.error("重置密码失败");
    }
//    -----------------------admin管理用户-----------------
    @GetMapping("/user/getAll")
    @Operation(summary = "获取所有用户")
    public Result getAll() {
        return Result.success(userService.list());
    }
    @PutMapping("/user/update")
    @Operation(summary = "启用禁用用户")
    @Transactional
    public Result update(@RequestBody User user) {
        if(user.getLockUser()==1){
            user.setLockUser(0);
            userService.updateById(user);
        }else {
            user.setLockUser(1);
            userService.updateById(user);
        }
        return Result.success();
    }
    @GetMapping("/auth/check-token")
    public Result validateToken(@RequestHeader("Authorization") String tokenHeader) {
        // Extract token from Authorization header (Bearer token)
        String token = tokenHeader.substring(7); // Remove "Bearer " prefix

        User user = userService.getByToken(token);
        return Result.success(user);
    }
}
